package com.happy.common.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.util.StringUtils;


public class HttpClientHelper {

    /**
     * 发送http请求
     *
     * @param map
     * @return
     * @throws IOException
     */
    public static Map doHttpRequset(Map<String, Object> map) throws Exception {
        Map<String, Object> repMap = new HashMap<>();

        // 创建httpClient实例对象
        HttpClient httpClient = new HttpClient();
        // 设置httpClient连接主机服务器超时时间：15000毫秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        // 根据请求方式创建请求方法实例对象
        String requestMethod = map.get("requestMethod") + "";
        String url = map.get("url") + "";
        String requestHeader = (String) map.get("requestHeader");
        String requestBody = (String) map.get("requestBody");
        HttpMethod httpMethod;
        if ("POST".equals(requestMethod)) {
            // 创建post请求方法实例对象
            httpMethod = new PostMethod(url);
            //添加请求参数
            if (!StringUtils.isEmpty(requestBody)) {
                JSONObject requestBodyJson = JSONObject.parseObject(requestBody);
                RequestEntity se = new StringRequestEntity(requestBodyJson.toString(), "application/json", "utf-8");
                if (httpMethod instanceof PostMethod) {
                    ((PostMethod) httpMethod).setRequestEntity(se);
                }
            }
        } else if ("GET".equals(requestMethod)) {
            // 创建GET请求方法实例对象
            httpMethod = new GetMethod(url);
        } else {
            throw new Exception("目前不支持该请求方式:+【" + requestMethod + "】");
        }
        // 设置请求超时时间
        httpMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 50000);
        httpMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
        //设置请求头
        if (!StringUtils.isEmpty(requestHeader)) {
            JSONObject requestHeaderJson = JSONObject.parseObject(requestHeader);
            Set<String> headerKeys = requestHeaderJson.keySet();
            for (String headerKey : headerKeys) {
                httpMethod.addRequestHeader(headerKey, requestHeaderJson.get(headerKey) + "");
            }
        }

        //执行请求
        int status = httpClient.executeMethod(httpMethod);
        String responseMsg = httpMethod.getResponseBodyAsString().trim();
        repMap.put("status",status);
        repMap.put("responseMsg",responseMsg);
        return repMap;
    }


    public static void main(String[] args) throws Exception {
//        String url = "http://localhost:8081/producer/get?name=11";
        String url = "http://localhost:8081/producer/post";
        Map<String, Object> map = new HashMap<>();
        map.put("requestMethod", "POST");
        map.put("url", url);
        map.put("requestHeader", null);
        map.put("requestBody", "{\"name\":\"张三\"}");
        Map jsonObject = doHttpRequset(map);
        System.out.println(jsonObject);
    }


    public static JSONObject doPost(String url) throws IOException {
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);

        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        //设置json格式传送
        postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
        //必须设置下面这个Header
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        //添加请求参数
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("url", "www.baidu.com");
        RequestEntity se = new StringRequestEntity(jsonObject.toString(), "application/json", "utf-8");
        postMethod.setRequestEntity(se);
        httpClient.executeMethod(postMethod);
        String responseMsg = postMethod.getResponseBodyAsString().trim();
        JSONObject returnJson = JSONObject.parseObject(responseMsg);
        return returnJson;
    }
}
